import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import routes from './routes'
import global from 'assets/utils/global'
import storage from 'assets/utils/storage'
import {
  Loading,

  //可选！，例如下面例子
  //使用的自定义旋转器
  QSpinnerGears
} from 'quasar'
Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */
const Router = new VueRouter({
  scrollBehavior: () => ({
    x: 0,
    y: 0
  }),
  routes,

  // Leave these as they are and change in quasar.conf.js instead!
  // quasar.conf.js -> build -> vueRouterMode
  // quasar.conf.js -> build -> publicPath
  mode: process.env.VUE_ROUTER_MODE,
  base: process.env.VUE_ROUTER_BASE
})
Router.beforeEach((to, from, next) => {

  const user = JSON.parse(window.localStorage.getItem('user'));
  if (to.meta.title) {
    document.title = to.meta.title;
  } else {

  };


  // 带Token登录

  if (user && to.path !== '/login') {
    // 有token 但不是去 login页面 通过
    next()
  } else if (user && to.path == '/login') {
    // 有token 但是去 login页面 不通过 重定向到首页
    next('/')
  };


  if (to.query.access_token) {
    let data = {
      access_token: to.query.access_token
    };
    axios({
      method: 'post',
      url: global.serveurl + '/tokenverify',
      data
    }).then(res => {
      if (res.data.code == 1) {
        window.localStorage.setItem('user', JSON.stringify(res.data));
        next();
      } else {
        next({ path: '/login', query: { redirect: to.fullPath } });
      }
    }).catch(err => {
      next({ path: '/login', query: { redirect: to.fullPath } });
    })
  }
  //
 else if (to.path == '/codepage') {
    next()

  }
  else if (to.path == '/qwcodepage') {
    next()

  }
  else if (to.path == '/workbench') {
    next()

  }
  else if (to.path == '/project'){
    next('/')
  }
  else if (to.path.match(/\/quotation/) ){
    next()
  }
  //审阅界面带code登录
  else if (to.params.work_id && to.query.code) {
    let code = to.query.code;
    axios({
      method: 'POST',
      url: global.serveurl + '/oa/user/fileloginverify',
      data: {
        code: code
      }
    }).then(res => {
      if (res.data.code == 1) {
        storage.setItem('userinfo', res.data.data);
        next()
      } else {
        next()
      }
    }).catch(() => {
      next()
    })

  }
  //审阅界面无需登录
  else if (to.params.work_id) {
    next()
  }

  //手机号登录注册
  else if (to.query.phonecode) {
    let code = to.query.code;
    axios({
      method: 'POST',
      url: global.serveurl + '/oa/user/phoneloginverify',
      data: {
        code: code,
        phonecode: to.query.phonecode,
        phonenum: to.query.phonenum
      }
    }).then(res => {
      if (res.data.code == 1) {
        storage.setItem('userinfo', res.data.data);
        storage.setItem('user', res.data);
        next()
      } else {
        next()
      }
    }).catch(() => {
      next()
    })

  }
  //快速登录
  else if (to.query.code) {
    //微信快速登录
    Loading.show({
      message: '正在登录……'
    })
    if(to.query.platform=='wechat'){
      let code = to.query.code;
      axios({
        method: 'POST',
        url: global.serveurl + '/oa/user/fileloginverify',
        data: {
          code: code
        }
      }).then(res => {
        Loading.hide()
        if (res.data.code == 1) {

          let user = { token: res.data.token };
          let userinfo = res.data.data;

          storage.setItem('user', user);
          storage.setItem('userinfo', userinfo);
          next(from.fullpath)
        } else {
          next('/login')
        }
      }).catch((err) => {

        Loading.hide()
        next('/login')
      })
    }else if (to.query.platform=='qw'){

      let code = to.query.code;
      axios({
        method: 'POST',
        url: global.serveurl + '/user/oaloginverify',
        data: {
          code: code
        }
      }).then(res => {
        if (res.data.code == 1) {
          console.log('load success');
          let user = { token: res.data.token };
          let userinfo = res.data.data;

          storage.setItem('user', user);
          storage.setItem('userinfo', userinfo);
          Loading.hide()
          next(from.fullpath)
        } else {
          Loading.hide()
          next('/login')
        }
      }).catch((err) => {
        Loading.hide()

        next('/login')
      })

    }else{
      Loading.hide()
    }

  }
  else if (!user && to.path !== '/login') {
    console.log('login confirm');
    // 没有token 但不是去 login页面 不通过（未登录不给进入）
    next({ path: '/login', query: { redirect: to.fullPath } });
  } else {
    // 剩下最后一种 没有token 但是去 login页面 通过
    next()
  }


})

export default Router
